import React from 'react'
import {useSelector, useDispatch} from 'react-redux';
import { asyncCheckTodo, asyncRemoveTodo } from '../../app/features/todoSlice';

export default function TodoMain() {
  //获取 dispatch 函数
  let dispatch = useDispatch();
  //获取 todos 
  let todos = useSelector(state => state.todo.value);
  return (
    <ul className="todo-main">
      {
        todos.map(item => {
          return <li key={item.id}>
                  <label>
                    <input type="checkbox" checked={item.done} onChange={(e) => {
                      //
                      dispatch(asyncCheckTodo({id: item.id,done:e.target.checked}))
                    }} />
                    <span className={item.done ? 'done' : null}>{item.title}</span>
                  </label>
                  <button className="btn btn-danger" onClick={async () => {
                    //删除指定 id 的任务, dispatch 在这里返回的结果永远为 『成功的 promise』
                    let res = await dispatch(asyncRemoveTodo(item.id));
                    //对异步任务的结果进行判断
                    if(res.type === 'todo/remove/fulfilled'){
                      alert('删除成功')
                    }else if(res.type === 'todo/remove/rejected'){
                      alert('删除失败');
                    }
                  }}>删除</button>
                </li>
        })
      }
      
      
    </ul>
  )
}
